//
//  UIButton+countDown.m
//  PointLegend
//
//  Created by 1dcq on 16/3/10.
//  Copyright © 2016年 CenturyGalaxyNetworkDevelopment. All rights reserved.
//

#import "UIButton+countDown.h"
#import <objc/runtime.h>

const void *titleKey = @"titleKey";
const void *timerKey = @"timerKey";

static int count = 90;

@implementation UIButton (countDown)

//- (void)dealloc
//{
//    NSLog(@"%s",__func__);
//}

- (void)startWithTime:(NSInteger)time btnNormalTitle:(NSString *)norTitle selectedTitle:(NSString *)selTitle normalColor:(UIColor *)norColor selectedColor:(UIColor *)selColor completeBlock:(void(^)())blcok
{
    __block NSInteger timeOut = time;
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_source_set_timer(_timer, dispatch_walltime(NULL, 0), 1.0*NSEC_PER_SEC, 0);
    dispatch_source_set_event_handler(_timer, ^{
    
        if (timeOut <= 0) {
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                self.enabled = YES;
                [self setBackgroundColor:norColor forState:UIControlStateNormal];
                [self setTitle:norTitle forState:UIControlStateNormal];
                if (blcok) { //倒计时完成
                    blcok();
                }
            });
        } else {
            int allTime = (int)time + 1;
            int seconds = timeOut % allTime;
            dispatch_async(dispatch_get_main_queue(), ^{
                self.enabled = NO;
                NSString *title = [NSString stringWithFormat:@"%@%dS",selTitle,seconds];
                [self setBackgroundColor:selColor forState:UIControlStateDisabled];
                [self setTitle:title forState:UIControlStateDisabled];
            });
            timeOut--;
        }
    });
    dispatch_resume(_timer);
}

-(void)startCountingDown
{
    self.enabled=NO;
    count = 90;
    objc_setAssociatedObject(self, titleKey, self.titleLabel.text, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(countDown:) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
    objc_setAssociatedObject(self, timerKey, timer, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (void)countDown:(NSTimer *)timer
{
    if (count==1) {
        NSTimer *timer = objc_getAssociatedObject(self, timerKey);
        [timer invalidate];timer=nil;
        self.enabled=YES;
        [self setTitle:objc_getAssociatedObject(self, titleKey) forState:UIControlStateNormal];
    }
    else
    {
        [self setTitle:[NSString stringWithFormat:@"%d秒后重发",count--] forState:UIControlStateNormal];
    }
}

@end
